#ifndef __LOGGER_HPP__
#define __LOGGER_HPP__

#include <iostream>
#include <string>
#include <memory>
#include <chrono>
#include <unistd.h>
#include <sstream>
#include <fstream>
#include <filesystem>
#include "Mutex.hpp"

// 日志等级
enum class LogLevel
{
    DEBUG,
    INFO,
    WARNING,
    ERRO,
    FATAL
};

std::string LevelToString(LogLevel level)
{
    switch (level)
    {
    case LogLevel::DEBUG:
        return "debug";
    case LogLevel::ERRO:
        return "erro";
    case LogLevel::FATAL:
        return "fatal";
    case LogLevel::INFO:
        return "info";
    case LogLevel::WARNING:
        return "warning";
    default:
        return "unknow";
    }
}

std::string GetTime()
{
    auto now = std::chrono::system_clock::now();
    std::time_t now_time = std::chrono::system_clock::to_time_t(now);
    std::tm *local_time = std::localtime(&now_time);
    char buffer[64];
    std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_time);
    return buffer;
}

// 基类刷新策略
class SyncFreshStrategy
{
public:
    virtual ~SyncFreshStrategy() = default;
    virtual void SyncStrategy(const std::string &message) = 0;
};
// 显示器策略
class MonitorStarategy : public SyncFreshStrategy
{
public:
    MonitorStarategy() {}
    void SyncStrategy(const std::string &message)
    {
        {
            LockGuarden lockguard(&_lock);
            std::cout << message.c_str() << std::endl;
        }
    }
    ~MonitorStarategy() {}

private:
    Mutex _lock;
};

const std::string initpath = "logger";
const static std::string initfilename = "Logger.txt";
// 文件策略
class FileStrategy : public SyncFreshStrategy
{
public:
    FileStrategy(const std::string &pathname = initpath, const std::string filename = initfilename)
        : _pathname(pathname), _filename(filename)
    {
        {
            LockGuarden lockguard(&_lock);
            if (std::filesystem::exists(_pathname))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_pathname);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << "\r\n";
            }
        }
    }
    void SyncStrategy(const std::string &message)
    {
        {
            LockGuarden lockguard(&_lock);
            std::string target=_pathname;
            target+="/";
            target+=_filename;
            std::ofstream out(target.c_str(),std::ios::app);
            if(!out.is_open())
            {
                std::cout<<"文件打开失败,返回"<<std::endl;
                return;
            }
            std::cout<<"文件打开成功"<<std::endl;
            out<<message<<"\n";
            out.close();
        }
    }
    ~FileStrategy() {}

private:
    std::string _pathname;
    std::string _filename;
    Mutex _lock;
};

// 采用策略模式
class Logger
{
public:
    Logger() {}
    void EnableMonitorStrategy()
    {
        _ptr = std::make_unique<MonitorStarategy>();
    }
    void EnableFileStrategy()
    {
        _ptr = std::make_unique<FileStrategy>();
    }
    class LogMessage
    {
    public:
        LogMessage(LogLevel level, std::string &filename, int line, Logger &logger)
            : _time(GetTime()), _level(level), _pid(getpid()), _filename(filename), _line(line), _logger(logger)
        {
            std::stringstream ss;
            ss << "[" << _time << "] [" << LevelToString(_level) << "] [" << _pid << "] [" << _filename << "] [" << _line << "]" << " - ";
            _message += ss.str();
        }

        template <typename T>
        LogMessage &operator<<(const T &info)
        {
            std::stringstream ss;
            ss << info;
            _message += ss.str();
            return *this;
        }
        ~LogMessage()
        {
            // 回调到上层
            if (_logger._ptr)
            {
                _logger._ptr->SyncStrategy(_message);
            }
        }

    private:
        // 【时间】【等级】【pid】【文件名】【行号】
        std::string _time;
        LogLevel _level;
        int _pid;
        std::string _filename;
        int _line;
        std::string _message;
        Logger &_logger;
    };
    LogMessage operator()(LogLevel level, std::string filename, int line)
    {
        return LogMessage(level, filename, line, *this);
    }
    ~Logger() {}

private:
    std::unique_ptr<SyncFreshStrategy> _ptr;
};

Logger logger;
#define LOG(level) logger(level, __FILE__, __LINE__)
#define EnableMonitorStrategy() logger.EnableMonitorStrategy()
#define EnableFileStrategy() logger.EnableFileStrategy()

#endif